import apiService from "@service/index";
import { saveUser } from "@slice/user";
import store from "@store/index";
export const userApiService = apiService
  .enhanceEndpoints({ addTagTypes: ["profile"] })
  .injectEndpoints({
    endpoints: (builder) => ({
      // 获取登录用户信息
      requestUser: builder.query({
        query: () => ({
          url: "/user",
          headers: {
            authorization: `Bearer ${store.getState().credentialsReducer.token}`,
          },
        }),
      }),
    }),
  })
  // 获取用户资料
  .injectEndpoints({
    endpoints: (builder) => ({
      // 获取用户资料
      requestProfile: builder.query({
        query: () => ({ url: "/user/profile" }),
        providesTags: ["profile"],
        async onQueryStarted(arg, api) {
          const response = await api.queryFulfilled;
          api.dispatch(saveUser(response.data.data));
        },
      }),
    }),
  })
// {profile:requestProfile的响应数据}
.injectEndpoints({
  endpoints: (builder) => ({
    // 修改头像
    uploadAvatar: builder.mutation({
      query: (formData) => ({
        url: "/user/photo",
        method: "PATCH",
        body: formData,
      }),
      invalidatesTags: ["profile"],
    }),
  }),
})
.injectEndpoints({
  endpoints: (builder) => ({
    // 更新用户资料
    updateProfile: builder.mutation({
      query: (profile) => ({ url: "/user/profile", method: "PATCH", body: profile }),
  		invalidatesTags: ["profile"],
    }),
  }),
})
.injectEndpoints({
  endpoints: (builder) => ({
    // 获取用户收藏列表
    collectlist: builder.query({
      query: () => ({ url: "/article/collections" }),
    }),
  }),
})
.injectEndpoints({
  endpoints: (builder) => ({
    // 获取用户阅读历史
    readlist: builder.query({
      query: () => ({ url: "/user/histories" }),
    }),
  }),
})
export const { useRequestUserQuery,useLazyRequestProfileQuery,useRequestProfileQuery, useUpdateProfileMutation,useUploadAvatarMutation,useCollectlistQuery,useReadlistQuery } = userApiService